package com.wocai.jrt.orgadmin.pay.action;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.vteba.web.action.GenericAction;
import com.vteba.web.action.JsonBean;
import com.vteba.web.editer.DoubleEditor;
import com.vteba.web.editer.IntEditor;
import com.vteba.web.editer.LongEditor;
import com.vteba.web.editer.StringEditor;
import com.wocai.jrt.orgadmin.employee.model.Employee;
import com.wocai.jrt.orgadmin.employee.service.spi.EmployeeService;
import com.wocai.jrt.orgadmin.pay.bean.PaySerialReqBean;
import com.wocai.jrt.orgadmin.pay.bean.PaySerialResBean;
import com.wocai.jrt.orgadmin.pay.model.PaySerial;
import com.wocai.jrt.orgadmin.pay.service.spi.PaySerialService;
import com.wocai.jrt.orgadmin.product.model.Product;
import com.wocai.jrt.orgadmin.product.model.ProductBean;
import com.wocai.jrt.orgadmin.product.service.spi.ProductService;
import com.wocai.jrt.orgadmin.utils.UserUtils;

/**
 * 支付流水控制器
 * 
 * @author yinlei
 * @date 2015-8-24 10:23:36
 */
@Controller
@RequestMapping("/paySerial")
public class PaySerialAction extends GenericAction<PaySerial> {
	private static final Logger LOGGER = LoggerFactory.getLogger(PaySerialAction.class);

	@Inject
	private PaySerialService paySerialServiceImpl;

	@Inject
	private EmployeeService employeeServiceImpl;
	
	@Inject
	private ProductService productServiceImpl;

	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		// 空字符串转换为null
		binder.registerCustomEditor(int.class, new IntEditor());
		binder.registerCustomEditor(long.class, new LongEditor());
		binder.registerCustomEditor(double.class, new DoubleEditor());
		binder.registerCustomEditor(String.class, new StringEditor());
		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat(
				"yyyy-MM-dd"), true));
	}

	/**
	 * 获取支付流水页面，仅仅只是页面而已
	 * 
	 * @param model
	 *            参数
	 * @return 产品List
	 */
	@RequestMapping("/list")
	public String list(PaySerialReqBean model) {
		return "pay/list";
	}

	/**
	 * 产品页面发起的产品查询请求，返回的是列表
	 * 
	 * @param model
	 *            参数
	 * @return 意见反馈List
	 */
	@ResponseBody
	@RequestMapping("/query")
	public Map<String, Object> query(@RequestBody PaySerialReqBean model) {
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			LOGGER.info("request PaySerialResBean query, param = [{}]", JSON.toJSONString(model));

			model.setOrgId(UserUtils.getUser().getOrgId());

			if (null != model.getPayEndTime()) {
				model.setPayEndTime(new DateTime(model.getPayEndTime()).plusSeconds(59)
						.plusMinutes(59).plusHours(23).toDate());
			}

			if (null != model.getOrderEndTime()) {
				model.setOrderEndTime(new DateTime(model.getOrderEndTime()).plusSeconds(59)
						.plusMinutes(59).plusHours(23).toDate());
			}

			int size = paySerialServiceImpl.fetchCount(model);
			if (model.getPageSize() == -1) {
				model.setStart(null);
			}

			List<PaySerialResBean> list = new ArrayList<PaySerialResBean>();

			if (size > 0) {
				list = paySerialServiceImpl.fetchPaySerial(model);
				LOGGER.info("query PaySerialResBean list success, size = [{}]", list.size());

			}

			map.put("aaData", list); // 返回的数据
			map.put("iTotalRecords", size); // 总记录数
			map.put("iTotalDisplayRecords", size); // 显示的记录数

		} catch (Exception e) {
			LOGGER.error("request PaySerialResBean query error, msg = [{}]", e.getMessage());
		}

		return map;
	}

	/**
	 * 查看支付流水详情页。
	 * 
	 * @param model
	 *            查询参数，携带ID
	 * @return 支付流水详情页
	 */
	@RequestMapping("/detail/{id}")
	public String detail(@PathVariable("id") String id, Map<String, Object> maps) {
		try {
			PaySerialReqBean psrParam = new PaySerialReqBean();
			psrParam.setId(id);
			psrParam.setOrgId(UserUtils.getUser().getOrgId());
			List<PaySerialResBean> model = paySerialServiceImpl.fetchPaySerial(psrParam);
			PaySerialResBean paySerialResBean = model.get(0);
			Integer auditState = paySerialResBean.getAuditState();
			if (null == auditState || auditState == 0) {
				paySerialResBean.setAuditId(null);
				paySerialResBean.setAuditName(null);
				paySerialResBean.setAuditTime(null);
			} else {
				Employee employee = employeeServiceImpl.get(paySerialResBean.getAuditId());
				paySerialResBean.setAuditName(employee.getName());
			}
			maps.put("paySerialResBean", paySerialResBean);// 将model放入视图中，供页面视图使用
		} catch (Exception e) {
			LOGGER.error("query record detail, errorMsg=[{}].", e.getMessage());
			return "common/error";
		}
		return "pay/detail";
	}
	
	/**
	 * 查看每日清算详情页。
	 * 
	 * @param model
	 *            查询参数，携带ID
	 * @return 支付流水详情页
	 */
	@RequestMapping("/dailyDetail/{id}")
	public String dailyDetail(@PathVariable("id") String id, Map<String, Object> maps) {
		try {
			PaySerialReqBean psrParam = new PaySerialReqBean();
			psrParam.setId(id);
			psrParam.setOrgId(UserUtils.getUser().getOrgId());
			List<PaySerialResBean> model = paySerialServiceImpl.fetchPaySerial(psrParam);
			PaySerialResBean paySerialResBean = model.get(0);
			Integer auditState = paySerialResBean.getAuditState();
			if (null == auditState || auditState == 0) {
				paySerialResBean.setAuditId(null);
				paySerialResBean.setAuditName(null);
				paySerialResBean.setAuditTime(null);
			} else {
				Employee employee = employeeServiceImpl.get(paySerialResBean.getAuditId());
				paySerialResBean.setAuditName(employee.getName());
			}
			maps.put("paySerialResBean", paySerialResBean);// 将model放入视图中，供页面视图使用
		} catch (Exception e) {
			LOGGER.error("query record detail, errorMsg=[{}].", e.getMessage());
			return "common/error";
		}
		return "pay/daily-detail";
	}
	
	/**
	 * 更新支付流水信息
	 * 
	 * @param model
	 *            要更新的支付流水信息，含有ID
	 * @return 操作结果信息
	 */
	@ResponseBody
	@RequestMapping("/audit/{id}")
	public JsonBean audit(@PathVariable("id") String id) {
		JsonBean bean = new JsonBean();
		try {
			PaySerial model = new PaySerial();
			model.setId(id);
			model.setAuditId(UserUtils.getUser().getEmployeeId());
			model.setAuditState(1);
			model.setAuditTime(new Date());
			int result = paySerialServiceImpl.updateById(model);
			if (result == 1) {
				bean.setMessage(SUCCESS);
				bean.setCode(1);
				LOGGER.info("update record success.");
			} else {
				bean.setMessage(ERROR);
				LOGGER.error("update record error.");
			}
		} catch (Exception e) {
			LOGGER.error("update record error, errorMsg=[{}].", e.getMessage());
			bean.setMessage(ERROR);
		}
		return bean;
	}
	
	/**
	 * autocomplete productBriefName
	 * 
	 * @param model
	 *            要更新的支付流水信息，含有ID
	 * @return 操作结果信息
	 */
	@ResponseBody
	@RequestMapping("/autocompleteProductBriefName/{key}")
	public List<Product> autocompleteProductBriefName(@PathVariable("key") String key) {
		List<Product> list = null;
		try {
			ProductBean productBean = new ProductBean();
			productBean.createCriteria().andBriefNameLike(key + "%").andOrgIdEqualTo(UserUtils.getOrgId());
			list = productServiceImpl.queryForList(productBean);
		} catch (Exception e) {
			LOGGER.error("autocompleteProductBriefName error, errorMsg=[{}].", e.getMessage());
		}
		return list;
	}
}
